<template>
  <a-upload
    :before-upload="beforeUpload"
    :customRequest="handleUpload"
    :showUploadList="false"
    :max-count="1"
    :accept="imageAccept"
  >
    <a-button :disabled="uploadLoading">
      <img src="@/assets/images/upload-icon.png" />
      点击上传
    </a-button>
    <div v-if="foldName.length" class="flex items-center">
      <div class="ml-1">{{ foldName }}</div>
    </div>
  </a-upload>
  <div v-for="i in fileList" :key="i.uid" class="file-uva">
    <img src="@/assets/images/upload-result.png" />
    {{ i.name }}
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import type { UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'

defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})

let flag = 0
const imageAccept = '.json,'
const fileList = ref<any>([])
const uploadLoading = ref(false)

const foldName = computed(() => {
  const path = fileList.value?.[0]?.webkitRelativePath
  return path ? path.substring(0, path.indexOf('/')) : ''
})

const resetDirectoryData = () => {
  flag = 0
  fileList.value = []
  uploadLoading.value = false
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase()

  fileList.value = []

  if (imageAccept.includes(fileType)) {
    fileList.value.push(file)
    return true
  } else {
    message.warning('文件格式仅支持.json')
    return false
  }
}

const handleUpload = () => {
  flag++
  if (flag === fileList.value?.length) {
    if (fileList.value?.length > 1) {
      resetDirectoryData()
      message.error('单次仅支持上传100张图片')
    }
  }
}

defineExpose({ fileList })
</script>

<style lang="less" scoped>
.ant-btn {
  display: flex;
  align-items: center;

  img {
    margin-right: 0.5rem;
    width: 1rem;
  }
}

.file-uva {
  display: flex;
  align-items: center;
  margin-top: 0.25rem;

  img {
    margin-right: 0.25rem;
    width: 1rem;
  }
}
</style>
